<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库配置 - 代码生成器</title>
    <link rel="icon" type="image/svg+xml" href="/favicon.svg">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #343a40;
        }
        .sidebar .nav-link {
            color: #fff;
        }
        .sidebar .nav-link:hover {
            background-color: #495057;
            color: #fff;
        }
        .sidebar .nav-link.active {
            background-color: #007bff;
            color: #fff;
        }
        .main-content {
            padding: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <h4 class="text-white">代码生成器</h4>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="/">
                                <i class="fa fa-home"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="/database-config">
                                <i class="fa fa-database"></i> 数据库配置
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/template-config">
                                <i class="fa fa-file-code-o"></i> 模板配置
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/code-gen">
                                <i class="fa fa-cogs"></i> 代码生成
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-10 ms-sm-auto main-content">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">数据库配置</h1>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#configModal">
                        <i class="fa fa-plus"></i> 添加配置
                    </button>
                </div>

                <!-- 数据库配置列表 -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <table class="table table-striped" id="configTable">
                                    <thead>
                                        <tr>
                                            <th>名称</th>
                                            <th>类型</th>
                                            <th>主机</th>
                                            <th>端口</th>
                                            <th>数据库</th>
                                            <th>用户名</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr th:each="config : ${configs}">
                                            <td th:text="${config.name}"></td>
                                            <td th:text="${config.dbType}"></td>
                                            <td th:text="${config.host}"></td>
                                            <td th:text="${config.port}"></td>
                                            <td th:text="${config.database}"></td>
                                            <td th:text="${config.username}"></td>
                                            <td>
                                                <span class="badge bg-warning">未测试</span>
                                            </td>
                                            <td>
                                                <button class="btn btn-sm btn-info me-1" onclick="testConnection(this)" th:data-id="${config.id}">
                                                    <i class="fa fa-link"></i> 测试
                                                </button>
                                                <button class="btn btn-sm btn-warning me-1" onclick="editConfig(this)" th:data-id="${config.id}">
                                                    <i class="fa fa-edit"></i> 编辑
                                                </button>
                                                <button class="btn btn-sm btn-danger" onclick="deleteConfig(this)" th:data-id="${config.id}">
                                                    <i class="fa fa-trash"></i> 删除
                                                </button>
                                            </td>
                                        </tr>
                                        <tr th:if="${#lists.isEmpty(configs)}">
                                            <td colspan="8" class="text-center text-muted">暂无数据库配置</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 配置模态框 -->
    <div class="modal fade" id="configModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">数据库配置</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="configForm">
                        <input type="hidden" id="configId" name="id">
                        
                        <div class="mb-3">
                            <label for="configName" class="form-label">配置名称</label>
                            <input type="text" class="form-control" id="configName" name="name" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="dbType" class="form-label">数据库类型</label>
                            <select class="form-select" id="dbType" name="dbType" required>
                                <option value="sqlite">SQLite</option>
                                <option value="mysql">MySQL</option>
                                <option value="postgresql">PostgreSQL</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="host" class="form-label">主机地址</label>
                            <input type="text" class="form-control" id="host" name="host" value="localhost" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="port" class="form-label">端口</label>
                            <input type="number" class="form-control" id="port" name="port" value="3306" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="database" class="form-label">数据库名</label>
                            <input type="text" class="form-control" id="database" name="database" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="password" class="form-label">密码</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="charset" class="form-label">字符集</label>
                            <input type="text" class="form-control" id="charset" name="charset" value="utf8">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveConfig()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 保存配置
        function saveConfig() {
            const form = document.getElementById('configForm');
            const formData = new FormData(form);
            const config = {};
            
            for (let [key, value] of formData.entries()) {
                config[key] = value;
            }
            
            console.log('准备保存配置:', config);
            
            // 验证必填字段
            if (!config.name || !config.dbType || !config.host || !config.port || !config.database || !config.username) {
                alert('请填写所有必填字段');
                return;
            }
            
            fetch('/database-config/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(config)
            })
            .then(response => {
                console.log('服务器响应状态:', response.status);
                if (!response.ok) {
                    throw new Error('HTTP状态: ' + response.status);
                }
                return response.text();
            })
            .then(data => {
                console.log('服务器返回数据:', data);
                if (data === 'success') {
                    alert('保存成功！');
                    // 关闭模态框
                    bootstrap.Modal.getInstance(document.getElementById('configModal')).hide();
                    // 重新加载页面
                    location.reload();
                } else {
                    alert('保存失败：' + data);
                }
            })
            .catch(error => {
                console.error('保存错误:', error);
                alert('保存失败：' + error.message);
            });
        }

        // 编辑配置
        function editConfig(button) {
            const configId = button.getAttribute('data-id');
            
            // 通过API获取配置信息
            fetch('/database-config/' + configId)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取配置失败');
                }
                return response.json();
            })
            .then(config => {
                console.log('获取到配置:', config);
                
                // 填充表单
                document.getElementById('configId').value = config.id || '';
                document.getElementById('configName').value = config.name || '';
                document.getElementById('dbType').value = config.dbType || 'sqlite';
                document.getElementById('host').value = config.host || '';
                document.getElementById('port').value = config.port || 3306;
                document.getElementById('database').value = config.database || '';
                document.getElementById('username').value = config.username || '';
                document.getElementById('password').value = config.password || '';
                document.getElementById('charset').value = config.charset || 'utf8';
                
                // 显示模态框
                new bootstrap.Modal(document.getElementById('configModal')).show();
            })
            .catch(error => {
                console.error('编辑配置错误:', error);
                alert('获取配置信息失败: ' + error.message);
            });
        }

        // 删除配置
        function deleteConfig(button) {
            if (!confirm('确定要删除这个配置吗？')) {
                return;
            }
            
            const configId = button.getAttribute('data-id');
            
            fetch('/database-config/' + configId, {
                method: 'DELETE'
            })
            .then(response => response.text())
            .then(data => {
                if (data === 'success') {
                    alert('删除成功！');
                    location.reload();
                } else {
                    alert('删除失败：' + data);
                }
            })
            .catch(error => {
                alert('删除失败：' + error);
            });
        }

        // 测试连接
        function testConnection(button) {
            const configId = button.getAttribute('data-id');
            const row = button.closest('tr');
            const statusCell = row.querySelector('td:nth-child(7)');
            
            button.disabled = true;
            button.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 测试中...';
            statusCell.innerHTML = '<span class="badge bg-warning">测试中...</span>';
            
            fetch('/database-config/test/' + configId, {
                method: 'POST'
            })
            .then(response => response.text())
            .then(data => {
                if (data.includes('成功')) {
                    statusCell.innerHTML = '<span class="badge bg-success">' + data + '</span>';
                } else {
                    statusCell.innerHTML = '<span class="badge bg-danger">' + data + '</span>';
                }
            })
            .catch(error => {
                statusCell.innerHTML = '<span class="badge bg-danger">测试失败</span>';
                console.error('测试连接错误:', error);
            })
            .finally(() => {
                button.disabled = false;
                button.innerHTML = '<i class="fa fa-link"></i> 测试';
            });
        }

        // 清空表单
        document.getElementById('configModal').addEventListener('hidden.bs.modal', function () {
            document.getElementById('configForm').reset();
            document.getElementById('configId').value = '';
            // 设置默认值
            document.getElementById('dbType').value = 'sqlite';
            document.getElementById('host').value = 'localhost';
            document.getElementById('port').value = 3306;
            document.getElementById('charset').value = 'utf8';
        });
    </script>
</body>
</html>